 //
//  AppDelegate.m
//  XiangLove
//
//  Created by 陈宪栋 on 2017/5/31.
//  Copyright © 2017年 陈宪栋. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+AutoLogin.h"
#import "BaiduMobStat.h"
#import "XLNavgationViewController.h"

#import "XLNewMainViewController.h"
#import "XLLoadingViewController.h"
#import "XLV2LoginViewController.h"

#import <UMCommon/UMCommon.h>
#import <UMAnalytics/MobClick.h>
#import <ImSDK/ImSDK.h>
#import "WXApiManager.h"
#import <WXApi.h>
#import "QQApiManager.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <ILiveSDK/ILiveSDK.h>
#import <TILCallSDK/TILCallManager.h>
#import "CallIncomingListenner.h"
#import <ReactiveCocoa.h>
//#import <lemon/LCLemonService.h>lemonsdk
#import <IQKeyboardManager/IQKeyboardManager.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

#import <NSString+DeviceId.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLHTTPSessionManager.h"

#import "XLMineViewController.h"
#import "XLOldMainTapViewController.h"
#import "BMHStoreObserver.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
#import <CoreTelephony/CTCellularData.h>
#endif
#import "XLTabBarController.h"
#import <IMSDKBugly/IMSDKBugly.h>
#import <AdSupport/AdSupport.h>
#import <QCloudCOSXML/QCloudCOSXML.h>
#import <QCloudCore.h>
#import "AppDelegate+AppService.h"

@interface AppDelegate ()<QCloudSignatureProvider>

@end

@implementation AppDelegate

#pragma mark - AppLifeCircle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"didFinishLaunching");
    // Override point for customization after application launch.
    //配置COS服务
    QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
    configuration.appID = @"10063237";
    configuration.signatureProvider = self;
    QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
    endpoint.regionName = @"ap-shanghai";//服务地域名称，可用的地域请参考注释
    configuration.endpoint = endpoint;
    
    [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
    [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
        NSLog(@"%@",granted ? @"麦克风准许":@"麦克风不准许");
    }];
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        NSLog(@"%@",granted ? @"相机准许":@"相机不准许");
    }];
    
    [self checkReviewStatus];   
    [self setupIQKeyBoard];
    [self registerRemoteNotification];
    [IMSDKBugly startWithAppId:@"d763f0415e"];
    
    
    //百度统计
    [[BaiduMobStat defaultStat] setChannelId:QudaoName];
    [[BaiduMobStat defaultStat] startWithAppId:BaiduAppid];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self getAppconfigList];
    
    //添加一个交易队列观察者
    [[SKPaymentQueue defaultQueue] addTransactionObserver:[BMHStoreObserver sharedInstance]];
    
#pragma firstLaunch
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
//    
    [self initAvoidCrash];
    
    [self getCurrentLocation];
    return YES;
}




- (NSString *)jsonStringWithDict:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (void) signatureWithFields:(QCloudSignatureFields*)fileds
                     request:(QCloudBizHTTPRequest*)request
                  urlRequest:(NSURLRequest*)urlRequst
                   compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
    /*向签名服务器请求临时的 Secret ID,Secret Key,Token*/
    QCloudCredential* credential = [QCloudCredential new];
    credential.secretID = @"AKIDimqZf4YCkASxaGFCllkbYc0SPxRAHcqX";
    credential.secretKey = @"cbNkPGIlRXh3TBaU2e3p9seEDVx2gh6d";
    credential.token = [[HelpTool getIOSuuid] substringToIndex:7];
    QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential];
    QCloudSignature* signature =  [creator signatureForData:urlRequst];
    continueBlock(signature, nil);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[IMAPlatformxl sharedInstance] configOnAppEnterBackground];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[IMAPlatformxl sharedInstance] configOnAppEnterForeground];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[IMAPlatformxl sharedInstance] configOnAppDidBecomeActive];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
    [[TIMManager sharedInstance] log:TIM_LOG_INFO tag:token msg:[NSString stringWithFormat:@"My Token is :%@", token]];
    TIMTokenParam *param = [[TIMTokenParam alloc] init];

#if DEBUG
        param.busiId = 11671;
#else
        param.busiId = 11670;
#endif
    
    
    [param setToken:deviceToken];
    [[TIMManager sharedInstance] setToken:param];
}

#pragma mark -
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    if ([options[UIApplicationOpenURLOptionsSourceApplicationKey] isEqualToString:@"com.tencent.mqq"]) {
        BOOL result = [QQApiInterface handleOpenURL:url delegate:[QQApiManager sharedManager]];
        if (result) {
            return result;
        }
        return [TencentOAuth HandleOpenURL:url];
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            int resultStatus = [resultDic[@"resultStatus"] intValue];
//            if (9000 == resultStatus) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"zhifusuccess" object:nil];
//                [HelpTool startTipViewWithText:@"支付成功" duration:1.0 type:kTipViewTypeNone];
//            } else {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"zhifushibai" object:nil];
//                [HelpTool startTipViewWithText:@"支付失败" duration:1.0 type:kTipViewTypeNone];
//            }
//        }];
    }
    return YES;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    NSString *payloadString = userInfo[@"payload"];
    if (payloadString == nil) return;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{

}
#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    if ([sourceApplication isEqualToString:@"com.tencent.mqq"]) {
        BOOL result = [QQApiInterface handleOpenURL:url delegate:[QQApiManager sharedManager]];
        if (result) {
            return result;
        }
        return [TencentOAuth HandleOpenURL:url];
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            int resultStatus = [resultDic[@"resultStatus"] intValue];
//            
//            if (9000 == resultStatus) {
//                
//                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"zhifusuccess" object:nil];
//                
//                [HelpTool startTipViewWithText:@"支付成功" duration:1.0 type:kTipViewTypeNone];
//            } else {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"zhifushibai" object:nil];
//                [HelpTool startTipViewWithText:@"支付失败" duration:1.0 type:kTipViewTypeNone];
//            }
//        }];
    }
    return YES;
}

- (void)registerRemoteNotification {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
}

#pragma mark - 第三方sdk初始化
- (void)setupTIM {
    NSString *TXAPPID = TIM_APP_ID_TEST;
    NSString *TXACCOUNTTYPE = TIM_ACCOUNT_TYPE_TEST;
    NSString *xlapi = BaseURL;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
        xlapi = @"http://test.xinliao.xiuquapp.com";
    }
    if ([xlapi isEqualToString:@"http://xinliao.xiuquapp.com"]) {
        TXAPPID = TIM_APP_ID;   TXACCOUNTTYPE = TIM_ACCOUNT_TYPE;
    }
    [[TIMManager sharedInstance] initSdk:[TXAPPID intValue] accountType:TXACCOUNTTYPE];
    [[ILiveSDK getInstance] initSdk:[TXAPPID intValue] accountType:[TXACCOUNTTYPE intValue]];
    [UMConfigure initWithAppkey:@"5a1d0cd8a40fa3242a0000f5" channel:QudaoName];
    
    [[TIMManager sharedInstance] addMessageListener:[IMAPlatformxl configWith:[IMAPlatformxlConfig new]].conversationMgr];
    [[TILCallManager sharedInstance] setIncomingCallListener:[[CallIncomingListenner alloc] init]];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
    //要消除警告的代码
    
    [[TencentOAuth alloc] initWithAppId:QQ_APP_ID andDelegate:nil];
#pragma clang diagnostic pop
    
    [WXApi registerApp:[UserDefaults objectForKey:wxGlobAppID] enableMTA:NO];
}

- (void)setupIQKeyBoard {
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:100.f];
}


#pragma mark - 设置根控制器
- (void)setupRootViewController {
    XLUserInfoModel *userInfoModel = [[XLAccountManager shareInstance] model];
    self.userInfoModel = userInfoModel;
    __weak typeof(self) weakSelf = self;
    //先判断有无本地登录信息
    if ([[UserDefaults objectForKey:UserToken] length] > 0 && userInfoModel != nil){//1
        
        __weak typeof(self) weakSelf = self;
        [self loginBoyibo:^(NSString *temp){
            
        } failBlock:^(NSString *temp){
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf setupLoginManViewController];
        }];
        XLTabBarController *mainVC = [[XLTabBarController alloc] init];
        self.window.rootViewController = mainVC;
        [self.window makeKeyAndVisible];
    }else{//没有登录信息去游客登录2
        if ([QudaoName isEqualToString:@"xinliao_openinstall_ios"]) {
            [self setupLoginManViewController];
        }else{
            [self autoLoginSuccessBlock:^(NSString *isYouke){
                //游客登录成功
                __strong typeof(weakSelf) strongSelf = weakSelf;
                XLTabBarController *mainVC = [[XLTabBarController alloc] init];
                strongSelf.window.rootViewController = mainVC;
                [strongSelf.window makeKeyAndVisible];

            } failBlock:^(NSString *isYouke){
                __strong typeof(weakSelf) strongSelf = weakSelf;
                [strongSelf setupLoginManViewController];
                
            }];
        }
    }
}


- (void)setupNewMainViewController {
    
    XLNewMainViewController *mainVC = [[XLNewMainViewController alloc] init];
    XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
    self.window.rootViewController = rootVC;
    [self.window makeKeyAndVisible];
    
}

- (void)setupOldMainViewController {
    XLTabBarController *mainVC = [[XLTabBarController alloc] init];
    self.window.rootViewController = mainVC;
    [self.window makeKeyAndVisible];
    
}

- (void)setupLoadingMainViewController {
    XLLoadingViewController *mainVC = [[XLLoadingViewController alloc] init];
    XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
    self.window.rootViewController = rootVC;
    [self.window makeKeyAndVisible];
}

- (void)setupLoginManViewController {
    XLV2LoginViewController *mainVC = [[XLV2LoginViewController alloc] init];
    mainVC.navigationItem.title = @"登录";
    XLNavgationViewController *rootVC = [[XLNavgationViewController alloc] initWithRootViewController:mainVC];
    self.window.rootViewController = rootVC;
    [self.window makeKeyAndVisible];
}

-(void)getAppconfigList
{
    [self setupLoadingMainViewController];
    [[[XLHTTPSessionManager sharedManager] getAppconfigLis] subscribeNext:^(id x) {
        NSLog(@"配置--%@",x);
        NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
        if ([success isEqualToString:@"0"] && [x[@"data"] isKindOfClass:[NSDictionary class]] == YES && [x[@"data"] isKindOfClass:[NSNull class]] == NO) {
            NSString * CompressionLeve = [NSString stringWithFormat:@"%@",x[@"data"][@"CompressionLeve"]];
            NSString * VideoLeve       = [NSString stringWithFormat:@"%@",x[@"data"][@"VideoLeve"]];
            NSString * WeChatAppId = [NSString stringWithFormat:@"%@",x[@"data"][@"WeChatAppId"]];
            [UserDefaults setObject:CompressionLeve forKey:CompressionLeveID];
            [UserDefaults setObject:VideoLeve       forKey:VideoLeveID];
            if ([WeChatAppId isEqualToString:[UserDefaults objectForKey:wxGlobAppID]] == NO) {
                [[XLAccountManager shareInstance] removeUserInfo];
            }
            
            if ([WeChatAppId isEqualToString:@"wx278d848f035a09ca"]) {
                [UserDefaults setObject:@"wx278d848f035a09ca"     forKey:wxGlobAppID];
                [UserDefaults setObject:@"2a81af61b1a6bc2ccf3dc0e0cec03de3"             forKey:wxGlobSECRET];
                [UserDefaults setObject:@"HZBoYiBoXiuQuWeiXinZhiFu20161212"             forKey:wxGlobPrivate];
            }else{
                [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
                [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
                [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
            }
        } else {
            [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
            [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
            [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
        }
        [self setupTIM];
        [self setupRootViewController];
        
    } error:^(NSError *error) {
        
        [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
        [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
        [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
        [self setupTIM];
        [self setupRootViewController];
    }];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state)
    { //获取联网状态 switch (state)
        switch (state) {
            case kCTCellularDataRestricted:
                NSLog(@"Restricrted");
                break;
            case kCTCellularDataNotRestricted: {
                NSLog(@"Not Restricted");
                if ([UserDefaults objectForKey:wxGlobAppID] == nil) {
                    [[[XLHTTPSessionManager sharedManager] getAppconfigLis] subscribeNext:^(id x) {
                        NSLog(@"配置--%@",x);
                        NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
                        if ([success isEqualToString:@"0"] && [x[@"data"] isKindOfClass:[NSDictionary class]] == YES && [x[@"data"] isKindOfClass:[NSNull class]] == NO) {
                            NSString * CompressionLeve = [NSString stringWithFormat:@"%@",x[@"data"][@"CompressionLeve"]];
                            NSString * VideoLeve       = [NSString stringWithFormat:@"%@",x[@"data"][@"VideoLeve"]];
                            NSString * WeChatAppId = [NSString stringWithFormat:@"%@",x[@"data"][@"WeChatAppId"]];
                            [UserDefaults setObject:CompressionLeve forKey:CompressionLeveID];
                            [UserDefaults setObject:VideoLeve       forKey:VideoLeveID];
                            
                            if ([WeChatAppId isEqualToString:@"wx278d848f035a09ca"]) {
                                [UserDefaults setObject:@"wx278d848f035a09ca"     forKey:wxGlobAppID];
                                [UserDefaults setObject:@"2a81af61b1a6bc2ccf3dc0e0cec03de3"             forKey:wxGlobSECRET];
                                [UserDefaults setObject:@"HZBoYiBoXiuQuWeiXinZhiFu20161212"             forKey:wxGlobPrivate];
                            }else{
                                [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
                                [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
                                [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
                            }
                        } else {
                            [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
                            [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
                            [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
                        }
                        [WXApi registerApp:[UserDefaults objectForKey:wxGlobAppID] enableMTA:NO];
                        
                    } error:^(NSError *error) {
                        
                        [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
                        [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
                        [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
                        [WXApi registerApp:[UserDefaults objectForKey:wxGlobAppID] enableMTA:NO];
                    }];
                }
            }
                break;
                //未知，第一次请求
            case kCTCellularDataRestrictedStateUnknown:
                NSLog(@"Unknown");
                break;
            default: break;
        }
    };
#else
    
#endif

}

#pragma mark - CheckReviewStatus
- (void)checkReviewStatus {

    CTCellularData *cellularData = [[CTCellularData alloc]init];
  
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state)
    { //获取联网状态 switch (state)
        NSLog(@"-------000-0--------%lu",(unsigned long)state);
        switch (state) {
                case kCTCellularDataRestricted:{
                    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
                    manager.cachePloy = XLHTTPCachePloy_Server;
                    [[manager checkReviewStatus] subscribeNext:^(id x) {
                        NSDictionary *dic = x;
                        NSDictionary *dicDta = [dic objectForKey:@"ApiData"];
                        if ([[dic objectForKey:@"ApiIntCode"] integerValue] == 1) {
                            if ([[dicDta objectForKey:@"IsVersionNum"] integerValue] == 1) {
                                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
                            } else {
                                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_IsSH];
                            }
                            if ([[dicDta objectForKey:@"IsShowApplePay"] integerValue] == 0) {
                                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_OpenApplePay];
                            } else {
                                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_OpenApplePay];
                            }
                            [[NSUserDefaults standardUserDefaults] synchronize];
                        }
                    } error:^(NSError *error) {
                        NSLog(@"Unknown7");
                        [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_OpenApplePay];
                        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }];
                }
                break;
                case kCTCellularDataNotRestricted: {
                    NSLog(@"Not Restricted");
            
                    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
                    manager.cachePloy = XLHTTPCachePloy_Server;
                    [[manager checkReviewStatus] subscribeNext:^(id x) {
                        NSDictionary *dic = x;
                        NSDictionary *dicDta = [dic objectForKey:@"ApiData"];
                        if ([[dic objectForKey:@"ApiIntCode"] integerValue] == 1) {
                            if ([[dicDta objectForKey:@"IsVersionNum"] integerValue] == 1) {
                                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
                            } else {
                                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_IsSH];
                            }
                            if ([[dicDta objectForKey:@"IsShowApplePay"] integerValue] == 1) {
                                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_OpenApplePay];
                            } else {
                                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_OpenApplePay];
                            }
                            [[NSUserDefaults standardUserDefaults] synchronize];
                        }
                    } error:^(NSError *error) {
                        NSLog(@"Unknown4");
                        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
                        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_OpenApplePay];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }];
                    //                }
                }
                break;
                //未知，第一次请求
                case kCTCellularDataRestrictedStateUnknown:
                NSLog(@"Unknown");
                break;
            default: break;
        }
    };
//#else
//    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
//    manager.cachePloy = XLHTTPCachePloy_Server;
//    [[manager checkReviewStatus] subscribeNext:^(id x) {
//        NSDictionary *dic = x;
//        NSDictionary *dicDta = [dic objectForKey:@"ApiData"];
//        if ([[dic objectForKey:@"ApiIntCode"] integerValue] == 1) {
//            if ([[dicDta objectForKey:@"IsVersionNum"] integerValue] == 1) {
//                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
//            } else {
//                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_IsSH];
//            }
//            if ([[dicDta objectForKey:@"IsShowApplePay"] integerValue] == 0) {
//                [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_OpenApplePay];
//            } else {
//                [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:XiangLove_OpenApplePay];
//            }
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
//    } error:^(NSError *error) {
//        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
//        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_OpenApplePay];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        NSLog(@"Unknown1");
//    }];
//#endif
    
}
@end
